// dh-medical_records 云对象 - 病例档案管理
const db = uniCloud.database();
const _ = db.command;
const { 
	autoMountHospitalId, 
	softDelete, 
	batchSoftDelete, 
	getUserById, 
	getUserList, 
	listDoctors, 
	listPatients,
	// 权限工具函数 - 从permission-utils.js导入
	MEDICAL_RECORD_PERMISSIONS,
	checkMedicalRecordViewPermission,
	checkMedicalRecordEditPermission,
	checkMedicalRecordDeletePermission,
	buildMedicalRecordQueryConditions,
	createTemporaryAuth,
	revokeTemporaryAuth,
	getUserTemporaryAuths,
	logPermissionAction,
	getUserAccessibleResources,
	hasAdminPermission
} = require('dh-common');

/**
 * 统一响应格式化辅助函数
 */
function formatResponse(code, data = null, message = 'success', extraFields = {}) {
	return {
		code,
		data,
		message,
		success: (code === 200 || code === 201),
		timestamp: Date.now(),
		...extraFields
	};
}

/**
 * 统一错误响应辅助函数
 */
function formatError(error, defaultMessage = '操作失败') {
	console.error('[dh-medical_records] 错误:', error);
	return {
		code: 500,
		message: error.message || defaultMessage,
		success: false,
		timestamp: Date.now()
	};
}

/**
 * 解析JWT Token获取payload
 */
function parseToken(token) {
	if (!token || typeof token !== 'string') return null;
	try {
		const parts = token.split('.');
		if (parts.length !== 3) return null;
		const payload = Buffer.from(parts[1], 'base64').toString('utf-8');
		return JSON.parse(payload);
	} catch (error) {
		console.error('[dh-medical_records] 解析token失败:', error);
		return null;
	}
}

/**
 * 获取当前用户信息和角色
 */
async function getCurrentUserInfo(userId) {
	try {
		// 使用统一的用户查询工具获取用户信息
		// 需要获取完整信息以包含 role，所以使用 'full' format
		// allowPatients 设置为 true，因为病例列表需要支持患者查看自己的病例
		// decryptSensitiveInfo 设置为 false，因为这里只需要角色信息，不需要解密敏感信息
		const userInfo = await getUserById(userId, 'full', true, false);
		
		if (userInfo) {
			return {
				_id: userInfo._id,
				role: userInfo.role,
				username: userInfo.username
			};
		}
		return null;
	} catch (error) {
		console.error('[dh-medical_records] 获取用户信息失败:', error);
		return null;
	}
}

/**
 * 检查用户是否有超级管理员权限（仅admin和manager）
 */
function isSuperAdmin(userRoles) {
	if (!Array.isArray(userRoles)) return false;
	return userRoles.some(role => ['admin', 'manager'].includes(role));
}

/**
 * 检查用户是否可以查看所有病例
 */
function canViewAllRecords(userRoles) {
	if (!Array.isArray(userRoles)) return false;
	return userRoles.some(role => ['admin', 'manager', 'director', 'vice_director', 'head_nurse'].includes(role));
}

/**
 * 检查用户是否有管理员权限（保留用于向后兼容）
 */
function isAdmin(userRoles) {
	if (!Array.isArray(userRoles)) return false;
	return userRoles.some(role => ['admin', 'manager', 'director', 'vice_director'].includes(role));
}

/**
 * 通过user_id查询dh-doctors表获取医生ID
 */
async function getUserDoctorId(userId) {
	try {
		if (!userId) return null;
		const doctorRes = await db.collection('dh-doctors')
			.where({ user_id: userId, is_deleted: false })
			.field({ _id: true })
			.get();
		if (doctorRes.data && doctorRes.data.length > 0) {
			return doctorRes.data[0]._id;
		}
		return null;
	} catch (error) {
		console.error('[getUserDoctorId] 查询失败:', error);
		return null;
	}
}

/**
 * 检查当前用户是否为指定病例的主治医师
 */
async function isRecordDoctor(userId, recordData) {
	try {
		if (!recordData || !recordData.doctor_id) return false;
		const doctorId = await getUserDoctorId(userId);
		return doctorId === recordData.doctor_id;
	} catch (error) {
		console.error('[isRecordDoctor] 检查失败:', error);
		return false;
	}
}

/**
 * 检查当前用户是否为指定病例的协助护士
 */
function isAssistingNurse(userId, recordData) {
	if (!recordData || !Array.isArray(recordData.assisting_nurses)) return false;
	return recordData.assisting_nurses.includes(userId);
}

/**
 * 检查用户是否有查看权限
 */
async function checkViewPermission(userId, recordData) {
	try {
		// 获取病例记录的医生ID和协助护士ID
		const recordDoctorId = recordData.doctor_user_id || null;
		const recordAssistantIds = recordData.assisting_nurses || [];
		
		// 使用权限工具检查查看权限
		const permissionResult = await checkMedicalRecordViewPermission(
			userId, 
			recordDoctorId, 
			recordAssistantIds
		);
		
		// 记录权限检查日志
		await logPermissionAction(userId, 'check_view_permission', {
			recordId: recordData._id,
			hasPermission: permissionResult.hasPermission,
			reason: permissionResult.reason
		});
		
		return permissionResult.hasPermission;
	} catch (error) {
		console.error('[dh-medical_records] 检查查看权限失败:', error);
		return false;
	}
}

/**
 * 检查用户是否有编辑权限
 */
async function checkEditPermission(userId, recordData) {
	try {
		// 获取病例记录的医生ID和协助护士ID
		const recordDoctorId = recordData.doctor_user_id || null;
		const recordAssistantIds = recordData.assisting_nurses || [];
		
		// 使用权限工具检查编辑权限
		const permissionResult = await checkMedicalRecordEditPermission(
			userId, 
			recordDoctorId, 
			recordAssistantIds
		);
		
		// 记录权限检查日志
		await logPermissionAction(userId, 'check_edit_permission', {
			recordId: recordData._id,
			hasPermission: permissionResult.hasPermission,
			reason: permissionResult.reason
		});
		
		return permissionResult.hasPermission;
	} catch (error) {
		console.error('[dh-medical_records] 检查编辑权限失败:', error);
		return false;
	}
}

module.exports = {

	/**
	 * 请求前拦截
	 */
	async _before(methodName, params) {
		const clientInfo = this.getClientInfo();
		const tokenString = clientInfo?.uniIdToken;
		const tokenPayload = parseToken(tokenString);

		if (!tokenPayload?.uid) {
			throw new Error('401|未授权的访问');
		}

		// 保存当前用户ID供后续方法使用
		this.currentUserId = tokenPayload.uid;

		if (params && typeof params === 'object') {
			for (let key in params) {
				if (typeof params[key] === 'string') {
					params[key] = params[key].trim();
				}
			}
		}
	},

	/**
	 * 获取病例详情
	 */
	async getMedicalRecordById(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '病例ID不能为空');
			}

			const res = await db.collection('dh-medical_records').doc(id).get();
			if (res.data.length === 0) {
				return formatResponse(404, null, '病例不存在');
			}

			const recordData = res.data[0];

			// 检查查看权限
			const hasPermission = await checkViewPermission(this.currentUserId, recordData);
			if (!hasPermission) {
				return formatResponse(403, null, '无权查看该病例');
			}

			// 查询患者信息
			if (recordData.patient_id) {
				const patientRes = await db.collection('dh-patients')
					.doc(recordData.patient_id)
					.get();
				if (patientRes.data.length > 0) {
					const patientInfo = patientRes.data[0];
					recordData.patient_info = patientInfo;
					
					// 获取患者姓名（优先使用用户表中的姓名，使用统一的用户查询工具）
					let patientName = patientInfo.patient_name || '未知';
					if (patientInfo.user_id) {
						const userInfo = await getUserById(patientInfo.user_id, 'default', true, true);
						if (userInfo) {
							patientName = userInfo.realName || userInfo.displayName || patientName;
						}
					}
					recordData.patient_name = patientName;
				}
			}

			// 查询医生信息（通过dh-doctors表）
			if (recordData.doctor_id) {
				const doctorRes = await db.collection('dh-doctors')
					.doc(recordData.doctor_id)
					.field({
						_id: true,
						user_id: true,
						title_level: true
					})
					.get();
				if (doctorRes.data && doctorRes.data.length > 0) {
					const doctor = doctorRes.data[0];
					// 使用统一的用户查询工具获取用户信息（自动解密）
					if (doctor.user_id) {
						const userInfo = await getUserById(doctor.user_id, 'default', false, true);
						if (userInfo) {
							const doctorName = userInfo.realName || userInfo.displayName || '未知';
							// 职称等级转换文本
							const titleMap = {
								0: '医士',
								1: '医师',
								2: '主治医师',
								3: '副主任医师',
								4: '主任医师'
							};
							const titleText = titleMap[doctor.title_level] || '';
							recordData.doctor_name = titleText ? `${doctorName} (${titleText})` : doctorName;
						}
					}
				}
			}

			// 查询协助护士姓名（使用统一的用户查询工具）
			if (recordData.assisting_nurses && Array.isArray(recordData.assisting_nurses) && recordData.assisting_nurses.length > 0) {
				const nurseNames = [];
				// 使用 getUserList 批量查询护士信息
				const allNurses = await getUserList({
					includeRoles: ['nurse'],
					format: 'default',
					limit: 1000,
					decryptSensitiveInfo: true
				});
				
				// 构建护士ID到姓名的映射
				const nurseMap = {};
				allNurses.forEach(nurse => {
					if (recordData.assisting_nurses.includes(nurse._id)) {
						nurseMap[nurse._id] = nurse.realName || nurse.displayName || '未知';
					}
				});
				
				// 按原始顺序构建护士姓名列表
				recordData.assisting_nurses.forEach(nurseId => {
					if (nurseMap[nurseId]) {
						nurseNames.push(nurseMap[nurseId]);
					}
				});
				
				recordData.nurse_names = nurseNames;
			} else {
				recordData.nurse_names = [];
			}

			// 检查编辑权限并添加到返回数据中
			const canEdit = await checkEditPermission(this.currentUserId, recordData);
			recordData.can_edit = canEdit;

			return formatResponse(200, recordData);
		} catch (error) {
			return formatError(error, '获取病例详情失败');
		}
	},

	/**
	 * 获取病例列表
	 * 根据当前用户角色自动过滤可查看的病例
	 */
	async listMedicalRecords(query = {}, skip = 0, limit = 20) {
		try {
			if (typeof query !== 'object' || query === null || Array.isArray(query)) {
				query = {};
			}
			skip = parseInt(skip) || 0;
			limit = parseInt(limit) || 20;

			// 使用权限工具构建查询条件
		let finalQuery = await buildMedicalRecordQueryConditions(this.currentUserId, query);

		// 默认不显示已删除记录
		finalQuery.is_deleted = false;

			// 查询基础权限的病例
			const countRes = await db.collection('dh-medical_records')
				.where(finalQuery)
				.count();

			let totalCount = countRes.total || 0;
			let recordsRes = await db.collection('dh-medical_records')
				.where(finalQuery)
				.skip(skip)
				.limit(limit)
				.orderBy('visit_date', 'desc')
				.get();

			// 对于非管理员，需要查询临时授权病例
			const userInfo = await getCurrentUserInfo(this.currentUserId);
			if (!canViewAllRecords(userInfo.role)) {
				const now = Date.now();
				// 查询有效的临时授权
				const authRes = await db.collection('dh-medical_authorizations')
					.where({
						authorized_user_id: this.currentUserId,
						start_time: _.lte(now),
						end_time: _.gte(now),
						is_active: true,
						can_view: true
					})
					.field({ record_id: true })
					.get();
				
				if (authRes.data.length > 0) {
					const authorizedRecordIds = authRes.data.map(a => a.record_id);
					
					// 查询临时授权的病例
					const authQuery = {
						...query,
						is_deleted: false,
						_id: _.in(authorizedRecordIds)
					};
					
					const authRecordsRes = await db.collection('dh-medical_records')
						.where(authQuery)
						.orderBy('visit_date', 'desc')
						.get();
					
					// 合并病例列表（去重）
					const existingIds = new Set(recordsRes.data.map(r => r._id));
					const newRecords = authRecordsRes.data.filter(r => !existingIds.has(r._id));
					recordsRes.data = [...recordsRes.data, ...newRecords];
					
					// 重新排序
					recordsRes.data.sort((a, b) => {
						const dateA = a.visit_date || 0;
						const dateB = b.visit_date || 0;
						return dateB - dateA;
					});
					
					// 计算总数（基础权限病例 + 临时授权病例，去重）
					// 先获取所有基础权限的病例ID
					const baseRecordIdsRes = await db.collection('dh-medical_records')
						.where(finalQuery)
						.field({ _id: true })
						.get();
					const baseRecordIds = baseRecordIdsRes.data.map(r => r._id);
					
					// 合并并去重
					const allRecordIds = new Set([...baseRecordIds, ...authorizedRecordIds]);
					totalCount = allRecordIds.size;
					
					// 应用分页
					recordsRes.data = recordsRes.data.slice(skip, skip + limit);
				}
			}

			// 批量查询患者和医生信息
			const patientIds = [...new Set(recordsRes.data.map(r => r.patient_id).filter(Boolean))];
			const doctorIds = [...new Set(recordsRes.data.map(r => r.doctor_id).filter(Boolean))];

			let patientsMap = {};
			let doctorsMap = {};

			// 查询患者信息（先查dh-patients表，再通过user_id关联uni-id-users获取姓名）
			if (patientIds.length > 0) {
				const patientsRes = await db.collection('dh-patients')
					.where({ _id: _.in(patientIds) })
					.field({
						_id: true,
						patient_name: true,
						user_id: true
					})
					.get();
				
				// 获取所有患者的user_id
				const patientUserIds = [...new Set(patientsRes.data.map(p => p.user_id).filter(Boolean))];
				
				// 批量查询用户信息（使用统一的用户查询工具）
				let usersMap = {};
				if (patientUserIds.length > 0) {
					// 使用 getUserList 查询所有患者用户，然后过滤出需要的
					const allPatients = await getUserList({
						includeRoles: ['patient'],
						allowPatients: true,
						format: 'default',
						limit: 1000,
						decryptSensitiveInfo: true
					});
					
					// 构建用户ID到姓名的映射
					allPatients.forEach(user => {
						if (patientUserIds.includes(user._id)) {
							usersMap[user._id] = user.realName || user.displayName || '未知';
						}
					});
				}
				
				// 构建患者信息映射（优先使用用户表中的姓名）
				patientsRes.data.forEach(p => {
					const patientName = usersMap[p.user_id] || p.patient_name || '未知';
					patientsMap[p._id] = {
						...p,
						patient_name: patientName
					};
				});
			}

			// 查询医生信息（先查dh-doctors表，再通过user_id关联uni-id-users）
			if (doctorIds.length > 0) {
				// 先查询dh-doctors表
				const doctorsRes = await db.collection('dh-doctors')
					.where({ _id: _.in(doctorIds) })
					.field({
						_id: true,
						user_id: true,
						title_level: true
					})
					.get();
				
				// 获取所有医生的user_id
				const doctorUserIds = [...new Set(doctorsRes.data.map(d => d.user_id).filter(Boolean))];
				
				// 批量查询用户信息（使用统一的用户查询工具）
				let usersMap = {};
				if (doctorUserIds.length > 0) {
					// 使用 getUserList 查询所有医生用户，然后过滤出需要的
					const allDoctors = await getUserList({
						includeRoles: ['doctor'],
						format: 'default',
						limit: 1000,
						decryptSensitiveInfo: true
					});
					
					// 构建用户ID到姓名的映射
					allDoctors.forEach(user => {
						if (doctorUserIds.includes(user._id)) {
							usersMap[user._id] = user.realName || user.displayName || '未知';
						}
					});
				}
				
				// 职称等级转换文本
				const titleMap = {
					0: '医士',
					1: '医师',
					2: '主治医师',
					3: '副主任医师',
					4: '主任医师'
				};
				
				// 构建医生信息映射
				doctorsRes.data.forEach(d => {
					const doctorName = usersMap[d.user_id] || '未知';
					const titleText = titleMap[d.title_level] || '';
					doctorsMap[d._id] = titleText ? `${doctorName} (${titleText})` : doctorName;
				});
			}

			// 合并数据，并为每个病例添加编辑权限字段
			const recordsList = await Promise.all(recordsRes.data.map(async (record) => {
				// 检查当前用户是否有编辑权限
				const canEdit = await checkEditPermission(this.currentUserId, record);
				
				return {
					_id: record._id,
					patient_id: record.patient_id,
					patient_name: patientsMap[record.patient_id]?.patient_name || '未知',
					doctor_id: record.doctor_id,
					doctor_name: doctorsMap[record.doctor_id] || '未知',
					visit_date: record.visit_date,
					diagnosis: record.diagnosis || '',
					symptoms: record.symptoms || '',
					treatment_plan: record.treatment_plan || '',
					status: record.status || 0,
					is_read_only: record.is_read_only || false,
					can_edit: canEdit,  // 添加编辑权限字段
					create_time: record.create_time,
					update_time: record.update_time
				};
			}));

			return formatResponse(200, recordsList, 'success', { count: totalCount });
		} catch (error) {
			return formatError(error, '获取病例列表失败');
		}
	},

	/**
	 * 创建病例
	 */
	async createMedicalRecord(data) {
		try {
		if (!data.patient_id || !data.doctor_id) {
			return formatResponse(400, null, '患者ID和医生ID不能为空');
		}

		let recordData = {
			patient_id: data.patient_id,
			doctor_id: data.doctor_id,
				visit_date: data.visit_date || Date.now(),
				symptoms: data.symptoms || '',
				diagnosis: data.diagnosis || '',
				treatment_plan: data.treatment_plan || '',
				prescription: data.prescription || [],
				examination_results: data.examination_results || [],
				images: data.images || [],
				notes: data.notes || '',
				assisting_nurses: data.assisting_nurses || [],
				status: data.status || 0,
				is_deleted: false,  // 软删除字段，默认未删除
				create_time: Date.now(),
			update_time: Date.now()
		};

		// 🏥 自动挂载医院ID（单一医院系统特性）
		recordData = await autoMountHospitalId(recordData);

		const res = await db.collection('dh-medical_records').add(recordData);
		return formatResponse(201, { _id: res.id }, '病例创建成功');
		} catch (error) {
			return formatError(error, '创建病例失败');
		}
	},

	/**
	 * 更新病例
	 */
	async updateMedicalRecord(id, data) {
		try {
			if (!id) {
				return formatResponse(400, null, '病例ID不能为空');
			}

			// 获取原病例数据
			const recordRes = await db.collection('dh-medical_records').doc(id).get();
			if (recordRes.data.length === 0) {
				return formatResponse(404, null, '病例不存在');
			}

			const recordData = recordRes.data[0];

			// 检查编辑权限
			const hasPermission = await checkEditPermission(this.currentUserId, recordData);
			if (!hasPermission) {
				return formatResponse(403, null, '无权编辑该病例');
			}

			const updateData = {
				...data,
				update_time: Date.now()
			};

			// 移除不应该更新的字段
			delete updateData._id;
			delete updateData.patient_id;
			delete updateData.hospital_id;
			delete updateData.create_time;

			await db.collection('dh-medical_records').doc(id).update(updateData);
			return formatResponse(200, null, '病例更新成功');
		} catch (error) {
			return formatError(error, '更新病例失败');
		}
	},

/**
 * 检查用户是否有删除权限
 */
async function checkDeletePermission(userId, recordData) {
		try {
			// 获取病例记录的医生ID和协助护士ID
			const recordDoctorId = recordData.doctor_user_id || null;
			const recordAssistantIds = recordData.assisting_nurses || [];
			
			// 使用权限工具检查删除权限
			const permissionResult = await checkMedicalRecordDeletePermission(
				userId, 
				recordDoctorId, 
				recordAssistantIds
			);
			
			// 记录权限检查日志
			await logPermissionAction(userId, 'check_delete_permission', {
				recordId: recordData._id,
				hasPermission: permissionResult.hasPermission,
				reason: permissionResult.reason
			});
			
			return permissionResult.hasPermission;
		} catch (error) {
			console.error('[dh-medical_records] 检查删除权限失败:', error);
			return false;
		}
	}

	/**
	 * 删除病例
	 */
	async deleteMedicalRecord(id) {
		try {
			if (!id) {
				return formatResponse(400, null, '病例ID不能为空');
			}

			// 获取原病例数据
			const recordRes = await db.collection('dh-medical_records').doc(id).get();
			if (recordRes.data.length === 0) {
				return formatResponse(404, null, '病例不存在');
			}

			const recordData = recordRes.data[0];

			// 检查删除权限
			const hasPermission = await checkDeletePermission(this.currentUserId, recordData);
			if (!hasPermission) {
				return formatResponse(403, null, '无权删除病例');
			}

			// 收集所有需要删除的图片URL
			const imageUrls = [];
			
			// 1. 收集影像资料中的图片
			if (recordData.images && Array.isArray(recordData.images)) {
				recordData.images.forEach(img => {
					if (typeof img === 'string' && img.startsWith('cloud://')) {
						imageUrls.push(img);
					} else if (typeof img === 'object' && img.url) {
						imageUrls.push(img.url);
					}
				});
			}
			
			// 2. 收集检查结果中的图片
			if (recordData.examination_results && Array.isArray(recordData.examination_results)) {
				recordData.examination_results.forEach(exam => {
					if (exam.images && Array.isArray(exam.images)) {
						exam.images.forEach(img => {
							if (typeof img === 'string' && img.startsWith('cloud://')) {
								imageUrls.push(img);
							} else if (typeof img === 'object' && img.url) {
								imageUrls.push(img.url);
							}
						});
					}
				});
			}
			
			// 删除检查结果中被移除的图片
			if (data.examination_results && Array.isArray(data.examination_results)) {
				// 收集更新前的图片URL
				const oldImageUrls = [];
				if (recordData.examination_results && Array.isArray(recordData.examination_results)) {
					recordData.examination_results.forEach(exam => {
						if (exam.images && Array.isArray(exam.images)) {
							oldImageUrls.push(...exam.images.filter(img => typeof img === 'string' && img.startsWith('cloud://')));
						}
					});
				}
				
				// 收集更新后的图片URL
				const newImageUrls = [];
				data.examination_results.forEach(exam => {
					if (exam.images && Array.isArray(exam.images)) {
						newImageUrls.push(...exam.images.filter(img => typeof img === 'string' && img.startsWith('cloud://')));
					}
				});
				
				// 找出需要删除的图片URL
				const imagesToDelete = oldImageUrls.filter(url => !newImageUrls.includes(url));
				if (imagesToDelete.length > 0) {
					imageUrls.push(...imagesToDelete);
				}
			}
			
			// 删除云存储中的图片（不阻塞软删除操作）
			if (imageUrls.length > 0) {
				try {
					await uniCloud.deleteFile({
						fileList: imageUrls
					});
					console.log(`[deleteMedicalRecord] 已删除 ${imageUrls.length} 个图片文件`);
				} catch (fileError) {
					console.error('[deleteMedicalRecord] 删除图片文件失败:', fileError);
					// 图片删除失败不影响软删除操作
				}
			}

			// 执行软删除（不删除关联的患者、医生、护士信息）
			const uniIdToken = this.getUniIdToken();
			const result = await softDelete('dh-medical_records', id, uniIdToken?.uid || '', '');
			
			if (result.code === 200) {
				return formatResponse(200, null, '病例已移至回收站');
			} else {
				return formatResponse(result.code, null, result.message);
			}
		} catch (error) {
			return formatError(error, '删除病例失败');
		}
	},

	/**
	 * 批量转移病例
	 * 将某医生的病例转给另一位医生
	 */
	async transferMedicalRecords(recordIds, newDoctorId, reason = '') {
		try {
			if (!Array.isArray(recordIds) || recordIds.length === 0) {
				return formatResponse(400, null, '病例ID列表不能为空');
			}

			if (!newDoctorId) {
				return formatResponse(400, null, '新医生ID不能为空');
			}

			// 只有管理员可以转移病例
			const userInfo = await getCurrentUserInfo(this.currentUserId);
			if (!userInfo || !isAdmin(userInfo.role)) {
				return formatResponse(403, null, '无权转移病例');
			}

			// 批量更新
			const promises = recordIds.map(id =>
				db.collection('dh-medical_records').doc(id).update({
					doctor_id: newDoctorId,
					transfer_history: _.push({
						from_doctor_id: 'previous_doctor',
						to_doctor_id: newDoctorId,
						transfer_by: this.currentUserId,
						transfer_date: Date.now(),
						reason: reason
					}),
					update_time: Date.now()
				})
			);

			await Promise.all(promises);
			return formatResponse(200, null, `成功转移${recordIds.length}条病例`);
		} catch (error) {
			return formatError(error, '转移病例失败');
		}
	},

	/**
	 * 创建临时授权
	 */
	async createTemporaryAuthorization(data) {
		try {
			if (!data.record_id || !data.authorized_user_id) {
				return formatResponse(400, null, '病例ID和被授权用户ID不能为空');
			}

			// 获取病例数据
			const recordRes = await db.collection('dh-medical_records').doc(data.record_id).get();
			if (recordRes.data.length === 0) {
				return formatResponse(404, null, '病例不存在');
			}

			const recordData = recordRes.data[0];

			// 使用权限工具创建临时授权
			const authResult = await createTemporaryAuth({
				resourceId: data.record_id,
				userId: this.currentUserId,
				targetUserId: data.authorized_user_id,
				permissions: {
					can_view: data.can_view !== undefined ? data.can_view : true,
					can_edit: data.can_edit !== undefined ? data.can_edit : false
				},
				startTime: data.start_time || Date.now(),
				endTime: data.end_time,
				reason: data.reason || '',
				resourceType: 'medical_record'
			});

			if (!authResult.success) {
				return formatResponse(403, null, authResult.message || '创建临时授权失败');
			}

			// 记录权限操作日志
			await logPermissionAction(this.currentUserId, 'create_temporary_auth', {
				record_id: data.record_id,
				authorized_user_id: data.authorized_user_id,
				can_view: data.can_view !== undefined ? data.can_view : true,
				can_edit: data.can_edit !== undefined ? data.can_edit : false,
				start_time: data.start_time || Date.now(),
				end_time: data.end_time,
				reason: data.reason || ''
			});

			return formatResponse(201, authResult.data, '临时授权创建成功');
		} catch (error) {
			return formatError(error, '创建临时授权失败');
		}
	},

	/**
	 * 撤销临时授权
	 */
	async revokeTemporaryAuthorization(authId) {
		try {
			if (!authId) {
				return formatResponse(400, null, '授权ID不能为空');
			}

			// 获取授权记录
			const authRes = await db.collection('dh-medical_authorizations').doc(authId).get();
			if (authRes.data.length === 0) {
				return formatResponse(404, null, '授权记录不存在');
			}

			const authData = authRes.data[0];

			// 权限检查：超级管理员/院长/副院长可以撤销任何授权，授权创建者可以撤销自己创建的授权
			const userInfo = await getCurrentUserInfo(this.currentUserId);
			if (!userInfo) {
				return formatResponse(403, null, '无权撤销授权');
			}

			let hasPermission = false;
			
			// 1. 超级管理员/院长/副院长：可以撤销任何授权
			if (canViewAllRecords(userInfo.role) || isSuperAdmin(userInfo.role)) {
				hasPermission = true;
			} else {
				// 2. 授权创建者：可以撤销自己创建的授权
				if (authData.authorized_by === this.currentUserId) {
					hasPermission = true;
				}
			}

			if (!hasPermission) {
				return formatResponse(403, null, '无权撤销授权');
			}

			await db.collection('dh-medical_authorizations').doc(authId).update({
				is_active: false,
				update_time: Date.now()
			});

			return formatResponse(200, null, '授权已撤销');
		} catch (error) {
			return formatError(error, '撤销授权失败');
		}
	},

	/**
	 * 获取病例的授权列表
	 */
	async listAuthorizationsByRecord(recordId) {
		try {
			if (!recordId) {
				return formatResponse(400, null, '病例ID不能为空');
			}

			// 检查病例访问权限
			const recordRes = await db.collection('dh-medical_records').doc(recordId).get();
			if (recordRes.data.length === 0) {
				return formatResponse(404, null, '病例不存在');
			}

			const hasPermission = await checkViewPermission(this.currentUserId, recordRes.data[0]);
			if (!hasPermission) {
				return formatResponse(403, null, '无权查看该病例的授权信息');
			}

			// 查询授权列表
			const authRes = await db.collection('dh-medical_authorizations')
				.where({ record_id: recordId })
				.orderBy('create_time', 'desc')
				.get();

			return formatResponse(200, authRes.data);
		} catch (error) {
			return formatError(error, '获取授权列表失败');
		}
	}
};

